Insertion sort is another simple sorting algorithm that builds the final sorted array one item at a time. It works by repeatedly taking an unsorted element and inserting it into its correct position in the sorted part of the array. Here's how it can implement insertion sort in C++:
#include <iostream>
void insertionSort(int arr[], int size) {
for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(arr) / sizeof(arr[0]);
std::cout << "Original array: ";
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
insertionSort(arr, size);
std::cout << "\nSorted array: ";
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
Original array: 64 34 25 12 22 11 90
Sorted array: 11 12 22 25 34 64 90
As it can see, the array is sorted in ascending order after applying the insertion sort algorithm.
question
question2